package com.changgou.oauth.token;

import com.alibaba.fastjson.JSON;
import org.junit.Test;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.jwt.Jwt;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.jwt.crypto.sign.RsaSigner;
import org.springframework.security.jwt.crypto.sign.RsaVerifier;
import org.springframework.security.oauth2.provider.token.store.KeyStoreKeyFactory;

import java.security.KeyPair;

import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;


/**
 * 实现令牌的创建和解析
 */
public class CreateJwtTestDemo {
    @Test
    public void testCreateToken(){
        //加载证书
        ClassPathResource resource=new ClassPathResource("changgou.jks");
        //读取证书数据
        KeyStoreKeyFactory keyStoreKeyFactory=new KeyStoreKeyFactory(resource,"changgou".toCharArray());
        //获取证书中的一对密钥
        KeyPair keyPair = keyStoreKeyFactory.getKeyPair("changgou","changgou".toCharArray());
        //获取私钥
        RSAPrivateKey privateKey = (RSAPrivateKey) keyPair.getPrivate();
        //创建令牌需要私钥加盐RSA算法
        Map<String,Object> payload=new HashMap<>();
        payload.put("nickname","tomcat");
        payload.put("address","sz");
        payload.put("role",new String[]{"admin","oauth"});
        Jwt jwt = JwtHelper.encode(JSON.toJSONString(payload), new RsaSigner(privateKey));
        //获取令牌数据
        String token= jwt.getEncoded();
        System.out.println(token);
    }

    @Test
    public void testParseToken(){
        String token="eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJhZGRyZXNzIjoic3oiLCJyb2xlIjoiYWRtaW4sdXNlciIsIm5pY2tuYW1lIjoidG9tY2F0In0.FMGMhkttI6gduDleoFYpLOTXLi-5R2aqjNGPdSX6hRoRv5wY7DeZj8z6MmLsYaeTHwps1MlFHjxLPfMKwjRFjS-kMzctnf5f22L5cqT3F7jWK5an0Gof_RxcxKyPGP-GP5chP6yNCx_gGLc2-sTFwAZbv3cKcxZHywwmbsnM_kbltUoXeFQ8XYRar0d9Rg4mjUmHHT3GPihDfnurYZFPzeeoB0DUXeORUK2A8WYi9UtPmHUPfWuKHlvay3xMWNbT7imk3NofdHZgWXk3N1WOUmOsvEunQEasz3JJKuQfL72RMQW2dewymitROOylpU4VSjAYTH1XdA22Ny9BH4jcDg";
        String publicKey="-----BEGIN PUBLIC KEY-----MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAvFsEiaLvij9C1Mz+oyAmt47whAaRkRu/8kePM+X8760UGU0RMwGti6Z9y3LQ0RvK6I0brXmbGB/RsN38PVnhcP8ZfxGUH26kX0RK+tlrxcrG+HkPYOH4XPAL8Q1lu1n9x3tLcIPxq8ZZtuIyKYEmoLKyMsvTviG5flTpDprT25unWgE4md1kthRWXOnfWHATVY7Y/r4obiOL1mS5bEa/iNKotQNnvIAKtjBM4RlIDWMa6dmz+lHtLtqDD2LF1qwoiSIHI75LQZ/CNYaHCfZSxtOydpNKq8eb1/PGiLNolD4La2zf0/1dlcr5mkesV570NxRmU1tFm8Zd3MZlZmyv9QIDAQAB-----END PUBLIC KEY-----";
        Jwt jwt = JwtHelper.decodeAndVerify(token, new RsaVerifier(publicKey));
        String claims = jwt.getClaims();
        System.out.println(claims);

    }
}
